package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-07
 * Time:14:19
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取到请求中的参数
        req.setCharacterEncoding("utf8");// 按照utf8的编码解析请求
        resp.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            resp.setContentType("text/html; character=utf8");
            resp.getWriter().write("当前的用户名或密码为空！");
            return;
        }
        // 2. 和数据可中的内容进行比较
        UserDAO userDAO = new UserDAO();
        User user = userDAO.selectByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            resp.setContentType("text/html; character=utf8");
            resp.getWriter().write("用户名或密码错误！");
            return;
        }
        // 3. 如果比较通过，就创建会话
        HttpSession session = req.getSession(true);
        // 把刚才的用户信息，存储到会话中
        session.setAttribute("user",user);//把user对象以键值对的形式加到会话中

        //4. 返回一个重定向报文，跳转页面
        resp.sendRedirect("blog_list.html");
    }

    // 检测当前的登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; character=utf8");
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 检测下会话是否存在，不存在说明未登录
            User user = new User();
            resp.getWriter().write(mapper.writeValueAsString(user));
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 虽然有会话，但是会话里没有user对象，也视为未登录
            user = new User();
            resp.getWriter().write(mapper.writeValueAsString(user));
            return;
        }
        // 已经登录的状态
        // 注意此处不要把密码返回给前端
        user.setPassword("");
        resp.getWriter().write(mapper.writeValueAsString(user));
    }
}
